package com.example.permission.controller;

import com.example.permission.common.Constants;
import com.example.permission.common.result.Result;
import com.example.permission.common.result.ResultCode;
import com.example.permission.common.utils.JwtUtil;
import com.example.permission.common.utils.Md5Util;
import com.example.permission.entity.po.SysAppInfo;
import com.example.permission.enums.TokenTypeEnum;
import com.example.permission.service.SysAppInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: xuwq
 * @date: 2020/7/22 10:41
 */
@Slf4j
@RestController
@RequestMapping("/api/token")
@Api(tags = "token接口")
public class TokenController {

    @Autowired
    private SysAppInfoService sysAppInfoService;

    /**
     * API Token
     *
     * @param appId
     * @param request
     * @return
     */
    @GetMapping("/api_token")
    @ApiOperation(value = "获取首次登录token")
    public Result<String> apiToken(String appId, HttpServletRequest request) {
        String timestamp = request.getHeader("timestamp");
        String sign = request.getHeader("sign");
        String nonce = request.getHeader("nonce");
        if (StringUtils.isBlank(appId) || StringUtils.isEmpty(timestamp) || StringUtils.isEmpty(sign)) {
            return Result.fail(ResultCode.HEADER_INVALID.getCode(), ResultCode.HEADER_INVALID.getMessage());
        }
        long requestInterval = System.currentTimeMillis() - Long.parseLong(timestamp);
        if (requestInterval > Constants.TIMEOUT) {
            return Result.fail(ResultCode.SYSTEM_TIMEOUT.getCode(), ResultCode.SYSTEM_TIMEOUT.getMessage());
        }
        // 1. 根据appId查询数据库获取appSecret
        SysAppInfo sysAppInfo = sysAppInfoService.queryByAppId(appId);
        if (sysAppInfo == null) {
            return Result.fail(ResultCode.APP_INFO_ERROR.getCode(), ResultCode.APP_INFO_ERROR.getMessage());
        }
        // 2. 校验签名
        String appKey = sysAppInfo.getAppKey();
        String signString = appId + appKey + timestamp + nonce;
        String signature = Md5Util.MD5(signString);
        if (!sign.equals(signature)) {
            return Result.fail(ResultCode.SYSTEM_SIGN_ERROR.getCode(), ResultCode.SYSTEM_SIGN_ERROR.getMessage());
        }
        // 3. 生成一个正确的token
        Map<String, String> map = new HashMap<>();
        map.put("appId", appId);
        map.put("appKey", appKey);
        map.put("tokenType", TokenTypeEnum.API.getCode());
        String token = JwtUtil.genToken(map);
        return Result.success(token);
    }

}
